<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodItem :good="good" />
      </li>
    </ul>
    <!-- 上啦加载更多 -->
    <XtxInfiniteLoad
      :isLoading="isLoading"
      :isFinished="isFinished"
      @load="getNextPage"
    />
  </div>
</template>

<script>
import GoodItem from './good-item'
import { findSubCategoryGoods } from '@/api/category.js'
import { ref, inject, watch } from 'vue'
import { useRoute } from 'vue-router'
// 抽离组件
function useList (filterParams) {
  const goodList = ref([])
  const route = useRoute()
  // 列表请求的参数
  const requestParams = {
    page: 0,
    pageSize: 20,
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  }
  // 实现上啦加载更多
  const isLoading = ref(false)
  const isFinished = ref(false)
  // const getGoodList = async () => {
  //   const res = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
  //   console.log(res.result.items)
  //   goodList.value = res.result.items
  // }
  // 上啦加载更多回调函数
  const getNextPage = async () => {
    isLoading.value = true
    requestParams.page++
    const res = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    goodList.value.push(...res.result.items)
    isLoading.value = false
    if (goodList.value.length === res.result.counts) {
      isFinished.value = true
    }
  }
  return { goodList, isLoading, requestParams, isFinished, getNextPage }
}
export default {
  components: {
    GoodItem
  },
  setup () {
    // 获取过滤条件数据
    const filterParams = inject('filterParams')
    // 处理列表钩子数据
    const { goodList, isLoading, requestParams, isFinished, getNextPage } = useList(filterParams)
    // 监控筛选条件变化，重新刷新列表
    watch(() => filterParams.value, () => {
      // console.log('变化', filterParams.value)
      goodList.value = []
      requestParams.page = 0
      isLoading.value = false
      isFinished.value = false
      // getGoodList()
    }, { deep: true })

    // onMounted(() => {
    //   getGoodList()
    // })

    return { goodList, isLoading, isFinished, getNextPage }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
